﻿using System.Collections.Generic;
using Game.Global.Helper;
using UnityEngine;

/// <summary>
/// 字符串内容提供，如提示信息、文本的本地化
/// </summary>
public class StringManager
{
    Dictionary<string, string> localStrDict;

    //直接读取配置，则可以按照需要实现内容：
    const string C_LocalizationPath = "StringManagerLocalization";

    protected static StringManager _instance;
    protected static StringManager instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = new StringManager();
            }

            return _instance;

        }
    }

    private StringManager()
    {
        var sysLanguage = Application.systemLanguage;
#if !UNITY_ANDROID
        localStrDict = FileHelper.LoadResource<Dictionary<string, string>>(C_LocalizationPath, sysLanguage.ToString());
#endif

        if( localStrDict == null)
        {
            localStrDict = new Dictionary<string, string>();
        }
    }

    /// <summary>
    /// 获得自定义枚举类型下的字符串，无则返回原类型
    /// </summary>
    /// <returns>The string.</returns>
    /// <param name="enumType">Enum type.</param>
    public static string GetStr(System.Enum enumType)
    {
        return instance.GetValOrKey(enumType.ToString());
    }

    /// <summary>
    /// 获得指定序号的字符串内容，无则返回原idx
    /// </summary>
    /// <returns>The string.</returns>
    /// <param name="dictIdx">Dict index.</param>
    public static string GetStr(int dictIdx)
    {
        return instance.GetValOrKey(dictIdx.ToString());
    }

    /// <summary>
    /// 获得自定义的key对应的内容，无则返回原str
    /// </summary>
    /// <returns>The string.</returns>
    /// <param name="selfDefineStr">Self define string.</param>
    public static string GetStr(string selfDefineStr)
    {
        return instance.GetValOrKey(selfDefineStr);
    }

    /// <summary>
    /// 获得值，如果不存在键值，编辑器模式下会添加之
    /// </summary>
    /// <returns>The value or empty.</returns>
    /// <param name="strKey">String key.</param>
    internal string GetValOrKey(string strKey)
    {
#if UNITY_ANDROID
        return strKey;
#endif

        if (localStrDict.ContainsKey(strKey))
        {
            return localStrDict[strKey];
        }
        else
        {
#if UNITY_EDITOR
            localStrDict.Add(strKey, strKey);
            FileHelper.Editor_SaveResource(C_LocalizationPath, Application.systemLanguage.ToString(), localStrDict, true);//保持序列化的格式文本可读
            Debug.LogWarning("Cannot get text for [" + strKey + "], currently will return key, but you should add it in localization file at :" + FileHelper.GetResourcesPath(C_LocalizationPath));

#endif
            return strKey;
        }
    }
}